package com.feedgraph;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

public class PlacesContentProvider extends ContentProvider {

	public static final String AUTHORITY = PlacesContentProvider.class
			.getCanonicalName ();
	private static final String DATABASE_NAME = "places.db";
	private static final int DATABASE_VERSION = 1;
	private static final int PLACES = 1;
	private static final int PLACE_ID = 2;

	private static final UriMatcher sUriMatcher;
	private static final HashMap<String, String> sProjectionMap; 

	@Override
	public int delete (Uri arg0, String where, String [] whereArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase ();
		return db.delete ("Places", where, whereArgs);
	}

	@Override
	public String getType (Uri uri) {
		switch (sUriMatcher.match (uri)) {
		case PLACES:
			return PlacesManager.PLACES_CONTENT_TYPE;
		default:

			throw new IllegalArgumentException ("Unknown URI " + uri);

		}

	}

	@Override
	public Uri insert (Uri uri, ContentValues values) {

		SQLiteDatabase db = dbHelper.getWritableDatabase ();
		long rowId = db.insertWithOnConflict ("Places", null, values, SQLiteDatabase.CONFLICT_REPLACE);
		if (rowId > 0) {
			Uri newUri = ContentUris.withAppendedId (PlacesManager.CONTENT_URI, rowId);
			getContext ().getContentResolver ().notifyChange (newUri, null);
			return newUri;
		}
		throw new SQLException ("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate () {
		 dbHelper = new DatabaseHelper(getContext());
		         return true;

	}

	@Override
	public Cursor query (Uri uri, String [] projection, String selection,
			String [] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables("Places");
    qb.setProjectionMap(sProjectionMap);

    switch (sUriMatcher.match(uri)) {    
        case PLACES:
            break;
        case PLACE_ID:
            selection = selection + "_id = " + uri.getLastPathSegment();
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
	}
	
	@Override
	public int update (Uri uri, ContentValues values, String selection,
			String [] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper (Context context) {
			super (context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate (SQLiteDatabase db) {
			
			String create = "CREATE TABLE Places ( _id TEXT PRIMARY KEY, Name TEXT, Icon TEXT, Longitude REAL, Latitude REAL, Radius REAL, TimeStamp TEXT)";
			
			Log.d (getClass().getSimpleName (), create);
			db.execSQL (create);
		}

		@Override
		public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w (getClass ().getSimpleName (), "Upgrading database from version "
					+ oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL ("DROP TABLE IF EXISTS Places");
			onCreate (db);
		}
	}

	private DatabaseHelper dbHelper;

	static {
		sUriMatcher = new UriMatcher (UriMatcher.NO_MATCH);
		sUriMatcher.addURI (AUTHORITY, "Places", PLACES);
		sUriMatcher.addURI (AUTHORITY, "Place/#", PLACE_ID);
		
		 sProjectionMap = new HashMap<String, String>();
		 sProjectionMap.put(PlacesManager.ID, PlacesManager.ID);
		 sProjectionMap.put(PlacesManager.NAME, PlacesManager.NAME);
		 sProjectionMap.put(PlacesManager.ICON, PlacesManager.ICON);
		 sProjectionMap.put(PlacesManager.LATITUDE, PlacesManager.LATITUDE);
		 sProjectionMap.put(PlacesManager.LONGITUDE, PlacesManager.LONGITUDE);
		 sProjectionMap.put(PlacesManager.RADIUS, PlacesManager.RADIUS);
		 sProjectionMap.put(PlacesManager.TIME_STAMP, PlacesManager.TIME_STAMP);

	}
}
